import path from 'node:path'
import process from 'node:process'
// IPC 处理器入口
import { BrowserWindow, ipcMain, Menu, nativeImage, Notification, Tray } from 'electron'
import { getLogsPath } from '../config/index'
import { getLogger } from '../logger/index'
import { getAutomationService } from '../services/automation-service'
import { setupAppointmentHandlers } from './appointment-handlers'
import { registerAutomationHandlers } from './automation-handlers'
import { setupBookingHandlers } from './booking-handlers'
import { setupConfigHandlers } from './config-handlers'
import { setupDatabaseHandlers } from './database-handlers'
import { setupLogHandlers } from './log-handlers'
import { setupProxyHandlers } from './proxy-handlers'
import { setupRemoteAppointmentHandlers } from './remote-appointment-handlers'
import { setupScriptHandlers } from './script-handlers'

export function setupIpcHandlers(): void {
  const logger = getLogger()

  try {
    // 注册各模块的 IPC 处理器
    // 脚本处理器
    setupScriptHandlers()
    // 配置处理器
    setupConfigHandlers()
    // 数据库处理器
    setupDatabaseHandlers()
    // 日志处理器
    setupLogHandlers()
    // 预约处理器
    setupAppointmentHandlers()
    // 自动化处理器
    registerAutomationHandlers()
    // 代理处理器
    setupProxyHandlers()
    // 远程预约处理器
    setupRemoteAppointmentHandlers()
    // 预约处理器
    setupBookingHandlers()
    // 系统处理器
    setupSystemHandlers()

    logger.info('✅ 所有 IPC 处理器注册完成')
  }
  catch (error) {
    logger.error('❌ IPC 处理器注册失败:', error)
    throw error
  }
}

/**
 * 设置系统处理器
 *
 * @description 设置系统处理器，包括托盘、任务栏关注等
 */
function setupSystemHandlers(): void {
  const logger = getLogger()
  let tray: Tray | null = null
  let trayDefaultImage: Electron.NativeImage | null = null
  let trayAlertImage: Electron.NativeImage | null = null
  let attentionOn = false

  /**
   * 确保托盘
   *
   * @description 确保托盘，如果已存在则返回，否则创建新托盘
   *
   * @returns {Tray} 托盘实例
   */
  function ensureTray(): Tray {
    if (tray)
      return tray
    try {
      const iconPath = path.join(__dirname, '../../resources/icon.png')
      trayDefaultImage = nativeImage.createFromPath(iconPath)
    }
    catch {}
    tray = new Tray(trayDefaultImage || undefined as any)
    tray.setToolTip('预约辅助工具')
    tray.setContextMenu(Menu.buildFromTemplate([
      { label: '打开窗口', click: () => {
        try {
          const win = BrowserWindow.getAllWindows()[0]
          if (win) {
            win.show()
            win.focus()
          }
        }
        catch {}
      } },
      { label: '暂停无人值守', click: async () => {
        try {
          await getAutomationService().stopAutomation()
        }
        catch {}
      } },
      { label: '退出', role: 'quit' },
    ]))
    return tray
  }

  /**
   * 获取红点图标
   *
   * @description 获取红点图标，如果已存在则返回，否则创建新红点图标
   *
   * @returns {Electron.NativeImage} 红点图标
   */
  function getRedDot(): Electron.NativeImage {
    if (trayAlertImage)
      return trayAlertImage
    // 16x16 红点 PNG
    const dataUrl = ''
    trayAlertImage = nativeImage.createFromDataURL(dataUrl)
    return trayAlertImage
  }

  // 系统：打开路径
  ipcMain.handle('system:open-path', async (_event, path: string) => {
    try {
      const { shell } = await import('electron')
      await shell.openPath(path)
      return { success: true }
    }
    catch (error) {
      logger.error('打开路径失败:', error)
      return { success: false, error: (error as Error).message }
    }
  })

  // 系统：在文件夹中显示
  ipcMain.handle('system:show-in-folder', async (_event, path: string) => {
    try {
      const { shell } = await import('electron')
      shell.showItemInFolder(path)
      return { success: true }
    }
    catch (error) {
      logger.error('在文件夹中显示失败:', error)
      return { success: false, error: (error as Error).message }
    }
  })

  // 系统：获取应用信息
  ipcMain.handle('system:app-info', async () => {
    try {
      const { app } = await import('electron')
      return {
        success: true,
        data: {
          name: app.getName(),
          version: app.getVersion(),
          path: app.getAppPath(),
          userData: app.getPath('userData'),
          platform: process.platform,
          arch: process.arch,
        },
      }
    }
    catch (error) {
      logger.error('获取应用信息失败:', error)
      return { success: false, error: (error as Error).message }
    }
  })

  // 系统：获取日志目录
  ipcMain.handle('system:get-logs-path', async () => {
    try {
      return { success: true, path: getLogsPath() }
    }
    catch (error) {
      logger.error('获取日志目录失败:', error)
      return { success: false, error: (error as Error).message }
    }
  })

  // 通知：可预约提醒（Windows Toast）
  ipcMain.handle('notify:available', async (_event, payload: { title: string, body: string }) => {
    try {
      const notif = new Notification({
        title: payload?.title || '发现可预约',
        body: payload?.body || '',
        silent: false,
        actions: [{ type: 'button', text: '打开窗口' }, { type: 'button', text: '暂停无人值守' }],
      })
      notif.on('click', () => {
        try {
          const win = BrowserWindow.getAllWindows()[0]
          if (win) {
            win.show()
            win.focus()
          }
        }
        catch {}
      })
      notif.on('action', async (_e, index) => {
        try {
          if (index === 0) {
            const win = BrowserWindow.getAllWindows()[0]
            if (win) {
              win.show()
              win.focus()
            }
          }
          else if (index === 1) {
            await getAutomationService().stopAutomation()
          }
        }
        catch {}
      })
      notif.show()
      return { success: true }
    }
    catch (error) {
      logger.warn('通知显示失败', { error: String(error) })
      return { success: false, error: String(error) }
    }
  })

  // 系统：任务栏关注（闪烁 + 覆盖图标 + 托盘红点）
  ipcMain.handle('system:attention', async (_event, on: boolean, tip?: string) => {
    try {
      const win = BrowserWindow.getAllWindows()[0]
      if (on) {
        attentionOn = true
        if (win?.flashFrame)
          win.flashFrame(true)
        try {
          win?.setOverlayIcon(getRedDot(), tip || '有可预约')
        }
        catch {}
        const t = ensureTray()
        try {
          t.setImage(getRedDot())
          t.setToolTip(tip || '有可预约')
        }
        catch {}
      }
      else {
        attentionOn = false
        try {
          win?.flashFrame(false)
        }
        catch {}
        try {
          win?.setOverlayIcon(null as any, '')
        }
        catch {}
        if (tray) {
          try {
            tray.setImage(trayDefaultImage || (nativeImage.createEmpty() as any))
            tray.setToolTip('预约辅助工具')
          }
          catch {}
        }
      }
      return { success: true, on: attentionOn }
    }
    catch (error) {
      logger.warn('设置任务栏关注失败', { error: String(error) })
      return { success: false, error: String(error) }
    }
  })
}
